package com.jiang.books.service.jpa;

import com.jiang.books.domain.User;
import com.jiang.books.service.IUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import java.math.BigInteger;
import java.util.List;

@Transactional
@Service
@Deprecated
public class UserServiceJpa implements IUserService {
    private Log log = LogFactory.getLog(UserServiceJpa.class);

    @PersistenceContext
    public EntityManager em;

    @Transactional(readOnly = true)
    public List<User> findAll() {
        List<User> users = em.createNamedQuery("User.findAll", User.class).getResultList();
        return users;
    }

    @Transactional(readOnly = true)
    public User findById(BigInteger id) {
        TypedQuery<User> query = em.createNamedQuery("User.findById", User.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    @Transactional(readOnly = false)
    public User save(User user) {
        if (user.getId() == null) {
            log.debug("Inserting new user");
            em.persist(user);
        } else {
            em.merge(user);
            log.debug("Updating existing user");
        }
        log.debug("user saved with id: " + user.getId());
        return user;
    }

    @Transactional(readOnly = false)
    public void delete(User user) {
        User mergedUser = em.merge(user);
        em.remove(mergedUser);
        log.debug("user with id: " + mergedUser.getId() + " deleted successfully");
    }
    
}